package com.rpc.protocal.codec;

import com.rpc.common.RpcRequest;
import com.rpc.common.constants.RpcConstants;
import com.rpc.protocal.RpcProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * RpcDecoder
 *
 * @author 春江花朝秋月夜
 * @since 2024/1/17 12:30
 */
public class RpcDecoder extends ByteToMessageDecoder {
    private static final short BASE_LENGTH=2+4;
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //数据是否合法，魔数是否 相同
        if (byteBuf.readableBytes()>BASE_LENGTH)
        {
            //数据包过大
            if (byteBuf.readableBytes()>1000)
            {
                byteBuf.skipBytes(byteBuf.readableBytes());
            }
            int beginReader;
            while (true)
            {
                beginReader=byteBuf.readerIndex();//当前索引
                byteBuf.markReaderIndex();
                if (byteBuf.readShort()== RpcConstants.MAGIC_NUMBER)
                {
                    break;
                }
                else
                {
                    channelHandlerContext.close();
                    return;
                }
            }
            int lenth=byteBuf.readInt();//消息的长度
            if (byteBuf.readInt()<lenth)
            {
                byteBuf.readerIndex(beginReader);//将当前读取位置放入
                return;
            }
            //开始读取消息
            byte[] readValue=new byte[lenth];
            byteBuf.readBytes(readValue);

            RpcProtocol<Object> rpcProtocol=new RpcProtocol<>();
            //放入读取后的数据
            rpcProtocol.setBody(readValue);
            list.add(rpcProtocol);
        }
    }
}
